package com.stylefeng.guns.rest.modular.wz.api.v3.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.common.exception.BizExceptionEnum;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.common.util.AliyunSmsUtil;
import com.stylefeng.guns.rest.common.util.StringUtils;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.*;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.api.v3.WzAdvMapApi;
import com.stylefeng.guns.rest.modular.wz.api.v3.dao.WzAdvMapDaoImpl;
import com.stylefeng.guns.rest.modular.wz.api.v3.service.IWzAdvMapService;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.controller.AsyncService;
import com.stylefeng.guns.rest.modular.wz.controller.WzFinanceService;
import com.stylefeng.guns.rest.modular.wz.dao.WzAdvDao;
import com.stylefeng.guns.rest.modular.wz.service.IPfFileService;
import com.stylefeng.guns.rest.modular.wz.service.IWzUserFinanceRecordService;
import com.stylefeng.guns.rest.modular.wz.service.IWzUserInfoService;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzAdminServiceImpl;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzAdvServiceImpl;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzUserAdvServiceImpl;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzUserServiceImpl;
import com.stylefeng.guns.rest.modular.wz.util.AliOssUtil;
import com.stylefeng.guns.rest.modular.wz.util.wz.DateUtil;
import org.dom4j.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * <p>
 * 广告地图表 服务实现类
 * </p>
 *
 * @author ruiyifeng123
 * @since 2018-09-25
 */
@Service
public class WzAdvMapServiceImpl extends ServiceImpl<WzAdvMapMapper, WzAdvMap> implements IWzAdvMapService {
    //网页标题
    private static String headTitle;
    //广告ID
    private static Long advId;
    //广告封面图
    private static String coverUrl;
    //分享链接
    private static String shareLink;
    //iosSchema
    private static String iosSchema = "waizhuan://";
    //androidSchema
    private static String androidSchema = "waizhuan://main.app";
    //广告分享api
    private static String ADV_SHARE_API = "http://wzapp.50waizhuan.com/wz/wzShare/api";
    //公众号id
    private static String MP_WX_APPID = "wxc1614bf9f778e4d6";
    //分享描述
    private static String shareDesc = "";
    //banner1
    public static final String banner1 = "http://oss.50waizhuan.com/02e5c479-708e-4c24-81c5-2008f1114beb.jpg";
    //banner2
    public static final String banner2 = "http://oss.50waizhuan.com/079e649c-3cfa-4733-bef5-ac0cd9b49cad.jpg";
    //banner3
    public static final String banner3 = "http://oss.50waizhuan.com/c2ab8905-7f04-4e14-bd3d-251fbbee2f2a.jpg";
    //topPic
    public static final String topPic = "http://oss.50waizhuan.com/e4bbf5c2-303a-40ea-8c06-21a3d41cf72a.jpg";
    //footbanner
    private static String footbanner = "http://oss.50waizhuan.com/429ce33b-43a0-4591-b615-6ef1d3942101.jpg";



    @Autowired
    private IPfFileService pfFileService;
    @Autowired
    private WzAdvMapServiceImpl wzAdvMapService;
    @Autowired
    private WzAdvServiceImpl wzAdvService;
    @Autowired
    private WzUserServiceImpl wzUserService;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private IWzUserInfoService wzUserInfoService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WzUserAdvRecordMapper userAdvRecordMapper;
    @Autowired
    private WzUserAdvMapper userAdvMapper;
    @Autowired
    private WzUserMapper userMapper;
    @Autowired
    private WzAdvDao advDao;
    @Autowired
    private WzAdvMapper advMapper;
    @Autowired
    private WzAdvMapMapper advMapMapper;
    @Autowired
    private WzUserFinanceRecordMapper userFinanceRecordMapper;
    @Autowired
    private WzAdvMapDaoImpl advMapDao;
    @Autowired
    private IWzUserFinanceRecordService userFinanceRecordService;
    @Autowired
    private AsyncService asyncService;
    @Autowired
    private WzAdminServiceImpl adminService;
    @Autowired
    private WzUserServiceImpl userService;
    @Autowired
    private WzUserAdvServiceImpl userAdvService;
    @Autowired
    private PfFileMapper pfFileMapper;
    @Autowired
    private WzAdvShareMapper advShareMapper;
    @Autowired
    private WzFinanceService financeService;
    @Autowired
    private WzMapActivityMapper mapActivityMapper;
    @Autowired
    private WzMapMergeMapper mapMergeMapper;
    @Autowired
    private WzMapRebateMapper mapRebateMapper;


    @Transactional
    public String createAdvMapShareHtml(String advMapDetailXML, String avatarUrl, String name, Long advMapId, Long userCode, WzUserInfo userInfo, String subtitle) throws UnsupportedEncodingException, DocumentException, FileNotFoundException {
        String fileUrl = advMapId + ".html";
        headTitle = name;
        StringBuilder sb = createAdvHtml(advMapDetailXML.replace("\n", "<![CDATA[<br/>]]>"), 0, avatarUrl, userInfo, subtitle);
        Boolean b = AliOssUtil.putStream(new ByteArrayInputStream(sb.toString().getBytes()), fileUrl, 5);
        if (b) {
            PfFile file = new PfFile();
            file.setName(headTitle);
            file.setType(EnPfFile.TYPE_Website.getIndex());
            file.setFileUrl(fileUrl);
            file.setStatus(EnPfFile.Status_Used.getIndex());
            file.setBucketName(Consts.bucketName_share);
            file.setUserCode(userCode);
            file.setCreateTime(new Date());
            file.setTargetId(advMapId.toString());
            file.setSubtype(EnPfFile.SUBTYPE_Website.getIndex());
            pfFileService.insert(file);
//            shareLink = Consts.DOMAIN_SHARE + fileUrl;
            return Consts.DOMAIN_SHARE + fileUrl;
        } else {
            return "";
        }
    }

    public StringBuilder createAdvHtml(String advMapDetail, Integer hasVideo, String avatarUrl, WzUserInfo userInfo, String subtitle) throws UnsupportedEncodingException, DocumentException {
        String merchantAddress=userInfo.getMerchantFulladdress();
        shareDesc = subtitle;
        StringBuilder sb = new StringBuilder();
        List<Map<String, Object>> nodeList = dom4j(advMapDetail);
        sb.append("<!DOCTYPE html>" +
                "<html>" +
                "<meta http-equiv='Content-Type' content='text/html:charset=UTF-8'>" +
                "<meta name='viewport' content='width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no' />" +
                "<meta name='apple-mobile-web-app-capable' content='yes' />" +
                "<link rel='stylesheet' href='http://oss.50waizhuan.com/wzAdvMap.css' type='text/css' />" +
                " <head>\n" +
                "<title>" + headTitle + "</title>\n" +
                "</head>\n" +
                "<body>\n");
        sb.append("   <div id=\"headBanner\" style=\"display: none\">\n" +
                        "        <div>\n" +
                "        <a href='javascript:;'><img class='headPic' src='" + banner1 + "' style='width:75.2%;'>\n" +
                "        </a>\n" +
                "        </div>\n" +
                "        <div>\n" +
                "        <a href='javascript:;' id='openApp'><img class='headPic' src='" + banner2 + "' style='left: 75.2%;width: 16.8%;' >\n" +
                "        </a>\n" +
                "        </div>\n" +
                "        <div >\n" +
                "        <a href='javascript:;'><img class='headPic' src='" + banner3+"' style='left: 92%;width: 8%;'   onclick=\"closeThis()\">\n" +
                "        </a>\n" +
                "        </div>\n" +
                "    </div>");
        sb.append("<div id='advMapHead' style='display: none'>\n" +
                "        <div class='logo'>\n" +
                "            <img id='avatarUrl' src='"+avatarUrl+"'>\n" +
                "        </div>\n" +
                "        <div>\n" +
                "            <div class='name'>"+headTitle+"</div>\n" +
                "            <div class='subtitle'>"+shareDesc+"</div>\n" +
                "        </div>\n" +
                "        <div style=\"clear:both\"></div>\n" +
                "\n" +
                "        <div class='merchantInfo'>\n" +
                "            <img class='address_png' src='http://oss.50waizhuan.com/5e6caabb-396a-4802-b0c8-6a90dd20344d.jpg'>\n" +
                "            <div class=\"address\">"+merchantAddress+"</div>\n" +
                "            <img class='telephon_png' src='http://oss.50waizhuan.com/f34fb6d0-c76c-46a2-82f9-5ddaf6dfcea6.jpg' tel='"+userInfo.getMerchantTel()+"'>\n" +
                "        </div>\n" +
                "    </div>"+
                "<div id='mapMergeData'></div>" +
                "<div id='mapRebateData'></div>" +
                "<div class='detail' id='dianpudetail' style='display: none'>店铺详情</div>");

        for (int i = 0; i < nodeList.size(); i++) {
            if ("{}".equals(nodeList.get(i).get("head").toString())) {
//                    System.out.println("noneHead");
            } else {
                Map<String, Object> map = (Map<String, Object>) nodeList.get(i).get("head");
                if (map.get("title") != null) {
                    sb.append("<div class='padding-20'><p class='titlefont'>" + map.get("title").toString() + "</p></div>");
                }
                if (map.get("image") != null) {
                    sb.append("<div><span><img src='" + map.get("image").toString() + "' width='100%'></span></div>");
                }
                if (map.get("html") != null) {
                    sb.append(map.get("html").toString());
                }
                if (hasVideo == 1) {
                    if (map.get("video") != null) {
                        sb.append("<div class='margin-15'><video style='width: 100%' poster='" + map.get("poster") + "' src='" + map.get("video").toString() + "' controls='controls'></video></div>");
                    }
                }
            }
            if ("[]".equals(nodeList.get(i).get("content").toString())) {
//                    System.out.println("noneContent");
            } else {
                List<Map<String, Object>> list = (List) nodeList.get(i).get("content");
                for (Map<String, Object> map : list) {
                    if (map.get("title") != null) {
                        sb.append("<div class='padding-20'><p class='titlefont'>" + map.get("title").toString() + "</p></div>");
                    }
                    if (map.get("text") != null) {
                        sb.append("<div class='margin-5'><p class='textfont'>" + map.get("text") + "</p></div>");
                    }
                    if (map.get("image") != null) {
                        if (map.get("margin") != null) {
                            String margin = map.get("margin").toString();
                            if ("true".equals(margin)) {
                                sb.append("<div class='margin-advMap-15'><span><img src='" + map.get("image").toString() + "' width='100%'></span></div>");
                            } else {
                                sb.append("<div><span><img src='" + map.get("image").toString() + "'  width='100%'></span></div>");
                            }
                        } else {
                            sb.append("<div class='margin-advMap-15'><span><img src='" + map.get("image").toString() + "' width='100%'></span></div>");

                        }
                    }
                    if (map.get("video") != null) {
                        sb.append("<div class='margin-15'><video style='width: 100%' poster='" + map.get("poster") + "' src='" + map.get("video").toString() + "' controls='controls'></video></div>");
                    }
                    if (map.get("html") != null) {
                        sb.append(map.get("html").toString());
                    }
                }
            }
        }
        sb.append("\n</body>\n" +
                "<input id=\"shareTitle\" style=\"display: none\" value='"+headTitle+"'>\n" +
                "<input id=\"shareDesc\" style=\"display: none\" value='"+shareDesc+"'>\n" +
                "<input id=\"shareImg\" style=\"display: none\" value='"+avatarUrl+"'>\n" +
                "</html>\n" +
                "<script src=\"https://code.jquery.com/jquery-3.0.0.min.js\"></script>\n" +
                "<script src=\"http://res.wx.qq.com/open/js/jweixin-1.2.0.js\"></script>\n" +
                "<script src=\"http://oss.50waizhuan.com/wzAdvMap.js\"></script>\n"
        );
        return sb;
    }

    public List<Map<String, Object>> dom4j(String detail) throws DocumentException, UnsupportedEncodingException {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> headMap = new HashMap<>();//head内容
        List<Map<String, Object>> tempList = new ArrayList<>();//其他内容
        Map<String, Object> Mapp = new HashMap<>();
        Document doc = DocumentHelper.parseText(detail);
        Element rootElt = doc.getRootElement();
        headTitle = rootElt.attributeValue("title");
        Iterator<Node> it = rootElt.nodeIterator();
        while (it.hasNext()) {
            Node node = it.next();
            //只有标签节点才有子节点 所以判断这个节点是否是标签节点
            if (node instanceof Element) {
                if ("head".equals(node.getName())) {
                    Element element = (Element) node;
                    Iterator<Node> itt = element.nodeIterator();
                    while (itt.hasNext()) {
                        Node nodee = itt.next();
                        if ("title".equals(nodee.getName())) {
                            headMap.put("title", ((Element) nodee).getTextTrim());
                        }
                        if ("image".equals(nodee.getName())) {
                            headMap.put("image", ((Element) nodee).attributeValue("src"));
                            headMap.put("size", ((Element) nodee).attributeValue("size"));
                        }
                        if ("video".equals(nodee.getName())) {
                            headMap.put("video", ((Element) nodee).attributeValue("src"));
                            headMap.put("poster", ((Element) nodee).attributeValue("thumb"));
                            headMap.put("size", ((Element) nodee).attributeValue("size"));
                        }
                        if ("html".equals(nodee.getName())) {
                            Map<String, Object> map = new HashMap<>();
                            byte[] bt = Base64Utils.decode(((Element) nodee).getTextTrim().getBytes());
                            String str = new String(bt, "utf-8");
                            headMap.put("html", str);
                        }
                    }
                } else {
                    if ("title".equals(node.getName())) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("title", ((Element) node).getTextTrim());
                        tempList.add(map);
                    }
                    if ("text".equals(node.getName())) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("text", ((Element) node).getTextTrim());
                        map.put("style", ((Element) node).attributeValue("style"));
                        map.put("color", ((Element) node).attributeValue("color"));
                        map.put("font", ((Element) node).attributeValue("font"));
                        tempList.add(map);
                    }
                    if ("image".equals(node.getName())) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("image", ((Element) node).attributeValue("src"));
                        map.put("size", ((Element) node).attributeValue("size"));
                        map.put("margin", ((Element) node).attributeValue("margin"));
                        tempList.add(map);
                    }
                    if ("video".equals(node.getName())) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("video", ((Element) node).attributeValue("src"));
                        map.put("poster", ((Element) node).attributeValue("thumb"));
                        map.put("size", ((Element) node).attributeValue("size"));
                        tempList.add(map);
                    }
                    if ("html".equals(node.getName())) {
                        Map<String, Object> map = new HashMap<>();
                        byte[] bt = Base64Utils.decode(((Element) node).getTextTrim().getBytes());
                        String str = new String(bt, "utf-8");
                        map.put("html", str);
                        tempList.add(map);
                    }
                }
            }
        }
        Mapp.put("head", headMap);
        Mapp.put("content", tempList);
        list.add(Mapp);
        return list;
    }


    @Transactional
    public Boolean updateAdvMap(WzAdvMap advMap, WzAdvMap advMapTemp) {
        Boolean p = wzAdvMapService.insert(advMapTemp);
        if (p) {
            Boolean q = wzAdvMapService.updateById(advMap);
            if (q) {
                return true;
            } else {
                return false;
            }

        }
        return false;
    }

    public Res userAdvReward(ParamMap paramMap,WzAdvMap advMap) {
        WzAdv adv = advMapper.selectById(Long.parseLong(advMap.getRedpacketAdvId().toString()));
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        //判断红包失效
        int userAdvRecordNumber = userAdvRecordMapper.selectCount(new EntityWrapper<WzUserAdvRecord>().eq("user_code", userCode).eq("adv_id", advMap.getRedpacketAdvId().toString()));
        if (adv.getStatus() >= EnWzAdv.STATUS_RELEASE_yes.getIndex() || (adv.getPushNumber() + 1) > adv.getTotalNumber() || userAdvRecordNumber > 0) {
            return Res.fail(BizExceptionEnum.ADV_SHIXIAO);
        }
        //红包领完处理
        adv.setPushNumber(adv.getPushNumber() + 1);
        if (adv.getPushNumber() >= adv.getTotalNumber()) {
            adv.setStatus(EnWzAdv.STATUS_RELEASE_yes.getIndex());
            advMap.setSubtype(EnWzAdvMap.SUBTYPE_Adv.getIndex());
            advMapMapper.updateById(advMap);
        }
        List<WzUserAdv> userAdvs = userAdvMapper.selectList(new EntityWrapper<WzUserAdv>().eq("adv_id", adv.getAdvId().toString()).eq("sort", adv.getPushNumber()));
        //随机金额处理
        int rewardAverage = userAdvs.get(0).getReward();
        WzUser user = cacheService.user(userCode);

        boolean r = financeService.repackedReward(adv,user,rewardAverage);
        if (r) {
            paramMap.clear();
            paramMap.put("reward", rewardAverage);
            return Res.success(paramMap);
        }
        return Res.fail();
    }


    /**
     * 地图广告数据列表
     */
    public ParamMap advMapData(ParamMap paramMap) {
        //必填
        String adCode = paramMap.getStrMisValid("adCode");//行政编号
        String leftTopLat = paramMap.getStrMisValid("leftTopLat");//左上角纬度
        String leftTopLng = paramMap.getStrMisValid("leftTopLng");//左上角经度
        String rightBottomLat = paramMap.getStrMisValid("rightBottomLat");//右下角纬度
        String rightBottomLng = paramMap.getStrMisValid("rightBottomLng");//右下角经度
        Integer showType = paramMap.getIntMisValid("showType");//展示类型数据:0-普通展示;1-缩放到街道;2-缩放到全市;
        //选填
        String advMapCategoryFirst = paramMap.getStrValid("advMapCategoryFirst");//一级分类
        String advMapCategorySecond = paramMap.getStrValid("advMapCategorySecond");//二级分类
        String advMapCategoryThird = paramMap.getStrValid("advMapCategoryThird");//三级分类
        String keyWords = paramMap.getStrValid("keyWords");//搜索关键字
        //sql语句
        EntityWrapper<WzAdvMap> ew = new EntityWrapper<>();
        boolean y = true;
        String sql = "adv_map_id AS advMapId,empty AS userCode,longitude,latitude,subtype,empty As merchantFullAddress,empty AS merchantTel,empty AS logo,empty AS avatarUrl,empty As subtitle,empty As name,empty As shareLink";
        ew.eq("type", EnWzAdvMap.TYPE_Adv.getIndex()).in("status", new Integer[]{EnWzAdvMap.STATUS_Release.getIndex(), EnWzAdvMap.STATUS_RelesseEditors.getIndex(), EnWzAdvMap.STATUS_Edit_Reject.getIndex()}).orderBy("daily_amount", false).orderBy("create_time", true);
        if (StringUtils.isNotBlank(advMapCategoryFirst)) {//一级筛选
            ew.eq("adv_map_category_first", advMapCategoryFirst);
            y = false;
        }
        if (StringUtils.isNotBlank(advMapCategorySecond)) {//二级筛选
            ew.like("adv_map_category_second", advMapCategorySecond);
            y = false;
        }
        if (StringUtils.isNotBlank(advMapCategoryThird)) {//三级筛选
            ew.like("adv_map_category_third", advMapCategoryThird);
            y = false;
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(keyWords)) {//关键字筛选
            String filterSql = "(name like '%" + keyWords+"%' or subtitle like '%"+keyWords+"%')";
            ew.addFilter(filterSql);
            y = false;
        } else {
            ew.ge("latitude", rightBottomLat).le("latitude", leftTopLat).ge("longitude", leftTopLng).le("longitude", rightBottomLng);
        }

        List<Map<String, Object>> advMaplist = new ArrayList<>();
        boolean r = false;
        if (showType == 0) {//基本地图广告
            advMaplist = wzAdvMapService.selectMaps(ew.setSqlSelect(sql));//广告地图数据
            r = true;
        } else if (showType == 1) {//缩放到街道
            sql = "adv_map_id AS advMapId,user_code AS userCode,longitude,latitude,subtype,merchant_tel AS merchantTel,logo AS logo,avatar_url AS avatarUrl,subtitle,name,share_link As shareLink,merchant_full_address As merchantFullAddress";
            advMaplist = wzAdvMapService.selectMaps(ew.setSqlSelect(sql));//广告地图数据
        } else if (showType == 2) {//缩放到全市
            advMaplist = wzAdvMapService.selectMaps(ew.setSqlSelect(sql));//广告地图数据
            r = true;
        }
        //靠前的数据显示完整
        if (r) {
            int j = WzAdvMapApi.advMapShowNumber;
            if (advMaplist.size() < j) {
                j = advMaplist.size();
            }
            for (int i = 0; i < j; i++) {
                WzAdvMap advMap = cacheService.advMap(Long.parseLong(advMaplist.get(i).get("advMapId").toString()));
                advMaplist.get(i).put("userCode", advMap.getUserCode());
                advMaplist.get(i).put("avatarUrl", advMap.getAvatarUrl());
                advMaplist.get(i).put("logo", advMap.getLogo());
                advMaplist.get(i).put("subtitle", advMap.getSubtitle());
                advMaplist.get(i).put("merchantFullAddress", advMap.getMerchantFullAddress());
                advMaplist.get(i).put("merchantTel", advMap.getMerchantTel());
                advMaplist.get(i).put("name", advMap.getName());
                advMaplist.get(i).put("shareLink", advMap.getShareLink());
            }
        }

        //置顶数据
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (y) {
            sql = "adv_map_id AS advMapId,user_code AS userCode,longitude,latitude,subtype,merchant_tel AS merchantTel,share_adv_id As shareAdvId,logo AS logo,avatar_url AS avatarUrl,subtitle,name,share_link As shareLink,merchant_full_address As merchantFullAddress,redpacket_adv_id As redpacketAdvId";
            List<Map<String, Object>> topAdvMapList = advMapMapper.selectMaps(new EntityWrapper<WzAdvMap>().setSqlSelect(sql).like("ad_code",adCode).eq("subtype", EnWzAdvMap.SUBTYPE_Redpacket_Adv.getIndex()).in("status", new Integer[]{EnWzAdvMap.STATUS_Release.getIndex(), EnWzAdvMap.STATUS_RelesseEditors.getIndex()}));
            Long userCode = jwtTokenUtil.getUserCodeFromToken();
            for (Map<String, Object> advMap : topAdvMapList) {
                int userAdvRecords = userAdvRecordMapper.selectCount(new EntityWrapper<WzUserAdvRecord>().eq("user_code", userCode).eq("adv_id", Long.parseLong(advMap.get("redpacketAdvId").toString())));
                if (userAdvRecords <= 0) {
                    advMap.remove("redpacketAdvId");
                    mapList.add(advMap);
                }
            }
        }
        paramMap.clear();
        paramMap.set("advMaplist", advMaplist);
        paramMap.set("topAdvMapList", mapList);
        return paramMap;
    }


    /**
     * 地图广告选择分类
     */
    @Override
    public Res advMapSelectCategory(ParamMap paramMap) {
        //必填
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        String leftTopLat = paramMap.getStrMisValid("leftTopLat");//左上角纬度
        String leftTopLng = paramMap.getStrMisValid("leftTopLng");//左上角经度
        String rightBottomLat = paramMap.getStrMisValid("rightBottomLat");//右下角纬度
        String rightBottomLng = paramMap.getStrMisValid("rightBottomLng");//右下角经度
        //选填
        String advMapCategoryFirst = paramMap.getStrValid("advMapCategoryFirst");//一级分类
        String advMapCategorySecond = paramMap.getStrValid("advMapCategorySecond");//二级分类
        String advMapCategoryThird = paramMap.getStrValid("advMapCategoryThird");//三级分类
        String keyWords = paramMap.getStrValid("keyWords");//搜索关键字
        //sql语句
        EntityWrapper<WzAdvMap> ew = new EntityWrapper<>();
        String sql = "adv_map_id AS advMapId,user_code AS userCode,longitude,latitude,subtype,merchant_tel AS merchantTel,logo AS logo,avatar_url AS avatarUrl,subtitle,name,share_link As shareLink,merchant_full_address As merchantFullAddress";
        ew.eq("type", EnWzAdvMap.TYPE_Adv.getIndex()).in("status", new Integer[]{EnWzAdvMap.STATUS_Release.getIndex(), EnWzAdvMap.STATUS_RelesseEditors.getIndex(), EnWzAdvMap.STATUS_Edit_Reject.getIndex()}).orderBy("daily_amount", false).orderBy("create_time", true);
        if (org.apache.commons.lang.StringUtils.isNotBlank(advMapCategoryFirst)) {//一级筛选
            ew.eq("adv_map_category_first", advMapCategoryFirst);
        }
        if (StringUtils.isNotBlank(advMapCategorySecond)) {//二级筛选
            ew.like("adv_map_category_second", advMapCategorySecond);
        }
        if (StringUtils.isNotBlank(advMapCategoryThird)) {//三级筛选
            ew.like("adv_map_category_third", advMapCategoryThird);
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(keyWords)) {
            ew.like("name", keyWords).or().like("subtitle", keyWords);
        } else {
            ew.ge("latitude", rightBottomLat).le("latitude", leftTopLat).ge("longitude", leftTopLng).le("longitude", rightBottomLng);
        }
        List<Map<String, Object>> advMaplist = advMapMapper.selectMapsPage(new Page<>(pageNum, pageSize), ew.setSqlSelect(sql));//广告地图数据
        return Res.success(paramMap.data(advMaplist));
    }

    /**
     * 新增周边店铺
     */
    public Res advMapAdd(ParamMap paramMap) throws Exception {
        //必填
        String logo = paramMap.getStrMisValid("logo");//logo
        String avatarUrl = paramMap.getStrMisValid("avatarUrl");//头像
        String name = paramMap.getStrMisValid("name");//名称
        String subtitle = paramMap.getStrMisValid("subtitle");//副标题
        String advMapDetailXML = paramMap.getStrMisValid("advMapDetail");//详情
        Integer subtype = paramMap.getIntMisValid("subtype");//类型
        Long advMapId = paramMap.getLongMisValid("advMapId");//id
        String advMapAdCode= paramMap.getStrValid("advMapAdCode");//地图广告发布区域

        //选填
        Long oldAdvMapId = paramMap.getLongValid("oldAdvMapId");//原来的店铺
        String advMapCategoryFirst = paramMap.getStrValid("advMapCategoryFirst");//一级分类
        String advMapCategorySecond = paramMap.getStrValid("advMapCategorySecond");//二级分类
        String link = paramMap.getStr("link");
        String linkName = paramMap.getStr("linkName");
        Integer expense = paramMap.getIntValid("expense");//总金额
        //驳回重新提交
        if (oldAdvMapId != null) {
            int r = advMapMapper.deleteById(oldAdvMapId);
        }
        //用户信息
        Long userInfoId = paramMap.getLongMisValid("userInfoId");
        WzUserInfo userInfo = wzUserInfoService.selectById(userInfoId);
        pfFileService.delete(new EntityWrapper<PfFile>().eq("status", 1).eq("subtype", EnPfFile.SUBTYPE_Website.getIndex()).lt("create_time", DateUtil.toString(new Date())));
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        WzUser user = cacheService.user(userCode);//发布用户
        String shareLink = wzAdvMapService.createAdvMapShareHtml(advMapDetailXML, logo, name, advMapId, userCode, userInfo, subtitle);//转网页
        WzAdvMap advMap = new WzAdvMap();
        if(StringUtils.isNotBlank(advMapAdCode)){
            advMap.setAdCode(advMapAdCode);
        }
        advMap.setUserCode(userCode);
        advMap.setName(name);
        advMap.setAvatarUrl(avatarUrl);
        advMap.setLogo(logo);
        advMap.setAdvMapDetail(advMapDetailXML);
        advMap.setAdvMapId(advMapId);
        advMap.setSubtitle(subtitle);
        advMap.setLatitude(userInfo.getMerchantLatitude());
        advMap.setLongitude(userInfo.getMerchantLongitude());
        advMap.setUserInfoId(userInfoId);
        advMap.setAdvMapCategoryFirst(advMapCategoryFirst);
        advMap.setAdvMapCategorySecond(advMapCategorySecond);
        advMap.setLink(link);
        advMap.setLinkName(linkName);
        advMap.setShareLink(shareLink);
        advMap.setStatus(EnWzAdvMap.STATUS_Checking.getIndex());
        advMap.setCreateTime(new Date());
        advMap.setMerchantFullAddress(userInfo.getMerchantFulladdress().substring(6,userInfo.getMerchantFulladdress().length()));
        advMap.setMerchantTel(userInfo.getMerchantTel());
        advMap.setSubtype(subtype);
        if (subtype == EnWzAdvMap.SUBTYPE_Adv.getIndex()) {//基本广告
            Integer dailyAmount = paramMap.getIntMisValid("dailyAmount");//日均金额
            Integer dayNumber = paramMap.getIntMisValid("dayNumber");//天数
            int expenses = dailyAmount * dayNumber;//广告发布费用
            if (user.getCashBalance() < expense) {
                return Res.fail("余额不足,请充值!");
            }
            if (expense != expenses || expense <= 0) {
                return Res.fail("金额异常!");
            }
            if (expense <= 0) {
                return Res.fail("金额不能为0!");
            }
            advMap.setTotalAmount(expense);
            advMap.setDayNumber(dayNumber);
            advMap.setDailyAmount(dailyAmount);
            advMap.setSubtype(EnWzAdvMap.SUBTYPE_Adv.getIndex());
            boolean r = financeService.advMapAdd(advMap, user,dailyAmount * dayNumber);
            if (r) {
                if (Consts.dev.equals("false")) {
                    for (String c : Consts.AuditorTel) {
                        SendSmsResponse response = AliyunSmsUtil.sendAdminSms(c, "有新的周边店铺需要审核", Consts.ADMIN_TEMPLATE_CODE);
                    }
                }
                return Res.success();
            } else {
                return Res.fail();
            }

        }
        return Res.fail();
    }


    //普通广告置顶
    @Override
    public Res setTopAdvMap(ParamMap paramMap) throws Exception {
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        WzUser user = cacheService.user(userCode);//发布用户
        Long advMapId = paramMap.getLongValid("advMapId");//id
        WzAdvMap advMap = wzAdvMapService.selectById(advMapId);
        //计算金额
        Integer totalNumber = paramMap.getIntMisValid("totalNumber");//总数量
        Integer expense = paramMap.getIntValid("expense");//总金额
        int rewardAverage = Integer.parseInt(Consts.rewardAverageMax) - Integer.parseInt(Consts.rewardAverageRate) * (totalNumber / Integer.parseInt(Consts.rewardAverageStep));//人均赏金
        if (rewardAverage < Integer.parseInt(Consts.rewardAverageMin)) {
            rewardAverage = Integer.parseInt(Consts.rewardAverageMin);
        }
        int expenses = rewardAverage * totalNumber;//广告发布费用
        if (expense != expenses) {
            return Res.fail("金额异常!");
        }
        if (user.getCashBalance() < expense) {
            return Res.fail("余额不足,请充值!");
        }
        advMap.setTotalAmount(advMap.getTotalAmount() + expense);
        Integer dayNumber = totalNumber / WzAdvMapApi.dayNumber;//天数
        Integer remainder = totalNumber % WzAdvMapApi.dayNumber;
        if (remainder > 0) {
            dayNumber = dayNumber + 1;
        }
        int serviceCharge = new BigDecimal(expense).multiply(new BigDecimal(Consts.redPacketFee)).setScale(0, BigDecimal.ROUND_UP).intValue();//广告服务费
        Date endTime = advMap.getEndTime();
        Date redPacketAdvEndTime = DateUtil.getDateAfter(new Date(), dayNumber + 1);
        //普通地图广告结束时间早于添加红包时间
        if (endTime.before(redPacketAdvEndTime)) {
            advMap.setEndTime(redPacketAdvEndTime);
        }
        //保存广告数据
        WzAdv adv = new WzAdv();
        Long advId = IdWorker.getId();
        advMap.setRedpacketAdvId(advId.toString());
        adv.setAdvId(advId);
        adv.setNickName(user.getNickName());
        adv.setAvatarUrl(user.getAvatarUrl());
        adv.setScreenCity(advMap.getAdCode());
        adv.setCoverUrl(advMap.getAvatarUrl());
        adv.setTitle(advMap.getName());
        adv.setSubtitle(advMap.getSubtitle());
        adv.setAdvDetail(advMap.getAdvMapDetail());
        adv.setUserCode(advMap.getUserCode());
        adv.setUserInfoId(advMap.getUserInfoId());
        adv.setShareLink(advMap.getShareLink());
        adv.setLink(advMap.getLink());
        adv.setLinkName(advMap.getLinkName());
        adv.setCreateTime(new Date());
        adv.setAdvMapId(advMap.getAdvMapId().toString());
        adv.setStatus(EnWzAdv.STATUS_RELEASE_no.getIndex());//状态
        adv.setSubtype(EnWzAdv.SUBTYPE_Redpacket_MapAdv.getIndex());//广告类型
        adv.setPublishingType(EnWzUserFinanceRecord.Publishing_type_user.getIndex());//发布类型：用户发布
        adv.setSubtitle(advMap.getSubtitle());
        adv.setRewardAverage(rewardAverage);//人均赏金金额
        adv.setTotalNumber(totalNumber);
        adv.setExpense(expense);
        adv.setEndTime(redPacketAdvEndTime);
        int totalReward = expense - serviceCharge;//赏金总额
        adv.setTotalReward(totalReward);//赏金总额
        adv.setSurplusReward(totalReward);//剩余赏金
        adv.setReleaseTime(new Date());//发布时间
        String start = DateUtil.toString(new Date()) + " 00:00:00";
        adv.setBeginTime(DateUtil.toDateTime(start));

        advMap.setRedpacketAdvId(advId.toString());
        advMap.setSubtype(EnWzAdvMap.SUBTYPE_Redpacket_Adv.getIndex());
        advMap.setStatus(EnWzAdvMap.STATUS_Release.getIndex());
        //生成红包数据
        userAdvService.delete(new EntityWrapper<WzUserAdv>().eq("adv_id", adv.getAdvId()));
        List<WzUserAdv> userAdvs = userService.userAdvs(adv);
        boolean r = financeService.saveSetTopAdvMap(user,adv,advMap,userAdvs,expense);
        if (r) {
            return Res.success();
        }
        return Res.fail();
    }

    //续费
    @Override
    public Res renewalsAdvMap(ParamMap paramMap) throws ParseException {
        Long advMapId = paramMap.getLongMisValid("advMapId");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        WzUser user = cacheService.user(userCode);//发布用户
        WzAdvMap advMap = wzAdvMapService.selectById(advMapId);
        Integer previousDailyAmount = advMap.getDailyAmount();//之前日均金额
        Integer dailyAmount = paramMap.getIntMisValid("dailyAmount");//日均金额
        Integer dayNumber = paramMap.getIntMisValid("dayNumber");//天数
        Integer appExpense = paramMap.getInt("expense");//金额
        Date previousEndTime = advMap.getEndTime();
        if (advMap.getStatus() != EnWzAdvMap.STATUS_Release.getIndex() && advMap.getStatus() != EnWzAdvMap.STATUS_Expired.getIndex()) {
            return Res.fail("当前不可续费 !");
        }
        if (dailyAmount < Integer.parseInt(Consts.miniDailyAmount)) {
            return Res.fail("日均金额至少1元!");
        }
        int expense = 0;
        if (dayNumber > 0) {
            if (advMap.getStatus() == EnWzAdvMap.STATUS_Expired.getIndex()) {
                previousEndTime = new Date();
            }
            previousEndTime = DateUtil.getDateAfter(previousEndTime, dayNumber);
        }
        int days = DateUtil.daysBetween(DateUtil.toString(new Date()), DateUtil.toString(previousEndTime));
        if (dayNumber > 0) {
            expense = (dailyAmount - previousDailyAmount) * (days - dayNumber) + dailyAmount * dayNumber;
        } else {
            expense = (dailyAmount - previousDailyAmount) * days;
        }
        if (expense != appExpense) {
            return Res.fail("金额异常!");
        }
        if (expense <= 0) {
            return Res.fail("金额不能是0!");
        }
        if (user.getCashBalance() < expense) {
            return Res.fail("余额不足,请充值!");
        }
        advMap.setTotalAmount(advMap.getTotalAmount() + expense);
        advMap.setDailyAmount(dailyAmount);
        advMap.setEndTime(previousEndTime);
        advMap.setStatus(EnWzAdvMap.STATUS_Release.getIndex());
        boolean r = financeService.renewalsAdvMap(advMap, user,expense);
        if (r) {
            return Res.success();
        } else {
            return Res.fail();
        }


    }
    public Res advMapEdit(ParamMap paramMap) throws Exception {
        String advMapAdCode= paramMap.getStrValid("advMapAdCode");//地图广告发布区域
        Long newAdvMapId = paramMap.getLongMisValid("newAdvMapId");//id
        String logo = paramMap.getStrMisValid("logo");//logo
        String avatarUrl = paramMap.getStrMisValid("avatarUrl");//头像
        String name = paramMap.getStrMisValid("name");//名称
        String subtitle = paramMap.getStrMisValid("subtitle");//副标题
        String advMapDetailXML = paramMap.getStrMisValid("advMapDetail");//详情
        Long userInfoId = paramMap.getLongMisValid("userInfoId");//地址
        String advMapCategoryFirst = paramMap.getStrValid("advMapCategoryFirst");//一级分类
        String advMapCategorySecond = paramMap.getStrValid("advMapCategorySecond");//二级分类
        Long oldAdvMapId = paramMap.getLongMisValid("oldAdvMapId");//原来的id
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        WzUserInfo userInfo = wzUserInfoService.selectById(userInfoId);
        //原来的地图广告
        WzAdvMap advMap = advMapMapper.selectById(oldAdvMapId);
        if (advMap.getStatus() != EnWzAdvMap.STATUS_Release.getIndex() && advMap.getStatus() != EnWzAdvMap.STATUS_Add_Reject.getIndex() && advMap.getStatus() != EnWzAdvMap.STATUS_Edit_Reject.getIndex()) {
            return Res.fail("不可以修改!");
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(advMap.getTargetId())) {
            advMapMapper.deleteById(Long.parseLong(advMap.getTargetId()));
//            List<PfFile> pfFiles = pfFileMapper.selectList(new EntityWrapper<PfFile>().eq("target_id", advMap.getTargetId()));
//            for (PfFile pfFile : pfFiles) {
//                AliOssUtil.deleteObject(pfFile.getFileUrl(), pfFile.getType(), pfFile.getBucketName());
//            }
//            pfFileMapper.delete(new EntityWrapper<PfFile>().eq("target_id", advMap.getTargetId()));
        }
        advMap.setTargetId(newAdvMapId.toString());
        advMap.setStatus(EnWzAdvMap.STATUS_RelesseEditors.getIndex());//修改状态
        //转网页
        String shareLink = createAdvMapShareHtml(advMapDetailXML, avatarUrl, name, newAdvMapId, userCode, userInfo, subtitle);
        //新建地图广告
        WzAdvMap advMapTemp = new WzAdvMap();
        if(StringUtils.isBlank(advMapAdCode)){
            advMapTemp.setAdCode(advMapAdCode);
        }
        advMapTemp.setAdvMapId(newAdvMapId);
        advMapTemp.setAvatarUrl(avatarUrl);
        advMapTemp.setLogo(logo);
        advMapTemp.setName(name);
        advMapTemp.setType(EnWzAdvMap.TYPE_Checking.getIndex());
        advMapTemp.setUserCode(userCode);
        advMapTemp.setSubtitle(subtitle);
        advMapTemp.setStatus(EnWzAdvMap.STATUS_RelesseEditors.getIndex());
        advMapTemp.setUserInfoId(userInfoId);
        advMapTemp.setAdCode(advMap.getAdCode());
        advMapTemp.setLongitude(userInfo.getMerchantLongitude());
        advMapTemp.setLatitude(userInfo.getMerchantLatitude());
        advMapTemp.setMerchantFullAddress(userInfo.getMerchantFulladdress().substring(6,userInfo.getMerchantFulladdress().length()));
        advMapTemp.setMerchantTel(userInfo.getMerchantTel());
        advMapTemp.setCreateTime(new Date());
        advMapTemp.setAdvMapDetail(advMapDetailXML);
        advMapTemp.setShareLink(shareLink);
        if (advMapCategoryFirst != null) {
            advMapTemp.setAdvMapCategoryFirst(advMapCategoryFirst);
        }
        if (advMapCategorySecond != null) {
            advMapTemp.setAdvMapCategorySecond(advMapCategorySecond);
        }
        //数据保存
        boolean r = advMapDao.advMapEdit(advMapTemp, advMap);
        if (r) {
            if (Consts.dev.equals("false")) {
                for (String c : Consts.AuditorTel) {
                    SendSmsResponse response = AliyunSmsUtil.sendAdminSms(c, "有周边店铺修改需要审核", Consts.ADMIN_TEMPLATE_CODE);
                }
            }
            return Res.success();
        }
        return Res.fail();
    }

    public Res advMapSearch(ParamMap paramMap) {
        String keyWords = paramMap.getStrMisValid("keyWords");//搜索关键字
        String switchAdCode = paramMap.getStrValid("switchAdCode");//行政编号
        if(org.apache.commons.lang.StringUtils.isBlank(switchAdCode)){
            switchAdCode= paramMap.getStrValid("adCode");
        }
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        String sql = "adv_map_id AS advMapId,subtype,avatar_url AS avatarUrl,subtitle,name,longitude,latitude,share_link As shareLink,merchant_tel As merchantTel";
        String filterSql = "(name like '%" + keyWords+"%' or subtitle like '%"+keyWords+"%')";
        List<Map<String, Object>> advMaplist = advMapMapper.selectMapsPage(new Page<>(pageNum, pageSize),new EntityWrapper<WzAdvMap>().setSqlSelect(sql)
                .addFilter(filterSql).like("ad_code", switchAdCode).eq("type", EnWzAdvMap.TYPE_Adv.getIndex()).in("status", new Integer[]{EnWzAdvMap.STATUS_Release.getIndex(), EnWzAdvMap.STATUS_RelesseEditors.getIndex(), EnWzAdvMap.STATUS_Edit_Reject.getIndex()}).orderBy("daily_amount", false));//周边店铺数据
        for(Map<String, Object> map:advMaplist){
            String mapActivitySql = "benefit";
            List<Map<String, Object>> mapActivitys = mapActivityMapper.selectMaps(new EntityWrapper<WzMapActivity>().setSqlSelect(mapActivitySql).eq("adv_map_id",Long.parseLong(map.get("advMapId").toString())).eq("status", EnWzMapActivity.STATUS_RELEASE.getIndex()).gt("surplus_number",0));
            map.put("mapActivitys",mapActivitys);
        }
        return Res.success(paramMap.data(advMaplist));
    }

    public Res newAdvMapSearch(ParamMap paramMap) {
        String keyWords = paramMap.getStrMisValid("keyWords");//搜索关键字
        String switchAdCode = paramMap.getStrValid("switchAdCode");//行政编号
        if(org.apache.commons.lang.StringUtils.isBlank(switchAdCode)){
            switchAdCode= paramMap.getStrValid("adCode");
        }
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        String sql = "adv_map_id AS advMapId,avatar_url AS avatarUrl,subtitle,name";
        String filterSql = "(name like '%" + keyWords+"%' or subtitle like '%"+keyWords+"%')";
        List<Map<String, Object>> advMaplist = advMapMapper.selectMapsPage(new Page<>(pageNum, pageSize),new EntityWrapper<WzAdvMap>().setSqlSelect(sql)
                .addFilter(filterSql).like("ad_code", switchAdCode).eq("type", EnWzAdvMap.TYPE_Adv.getIndex()).in("status", new Integer[]{EnWzAdvMap.STATUS_Release.getIndex(), EnWzAdvMap.STATUS_RelesseEditors.getIndex(), EnWzAdvMap.STATUS_Edit_Reject.getIndex()}).orderBy("daily_amount", false));//周边店铺数据
        for(Map<String, Object> map:advMaplist){
            int i = 0;
            List<Map<String, Object>> mapActivityList = new ArrayList<>();
            String mapRebateSql = "'' As mapMergeId,map_rebate_id As mapRebateId,benefit,rebate_price As price";
            List<Map<String, Object>> mapRebateList = mapRebateMapper.selectMaps(new EntityWrapper<WzMapRebate>().setSqlSelect(mapRebateSql).eq("adv_map_id",Long.parseLong(map.get("advMapId").toString())).eq("status",EnWzMapRebate.STATUS_RELEASE.getIndex()).orderBy("create_time",true));
            String mapMergeSql = "map_merge_id As mapMergeId,'' As mapRebateId,benefit,merge_price As price";
            List<Map<String, Object>> mapMergeList = mapMergeMapper.selectMaps(new EntityWrapper<WzMapMerge>().setSqlSelect(mapMergeSql).eq("adv_map_id",Long.parseLong(map.get("advMapId").toString())).eq("status",EnWzMapMerge.STATUS_RELEASE.getIndex()).orderBy("create_time",true));
            if(mapRebateList.size() > 0){
                mapActivityList.add(mapRebateList.get(0));
                i++;
            }
            if(mapMergeList.size() > 0){
                mapActivityList.add(mapMergeList.get(0));
                i++;
            }
            if(mapRebateList.size() > 1){
                mapActivityList.add(mapRebateList.get(1));
                i++;
            }
            if(mapMergeList.size() > 1 && i < 4){
                mapActivityList.add(mapMergeList.get(1));
                i++;
            }
            if(mapRebateList.size() > 2 && i < 4){
                mapActivityList.add(mapRebateList.get(2));
                i++;
            }
            if(mapMergeList.size() > 2 && i < 4){
                mapActivityList.add(mapMergeList.get(2));
            }
            map.put("mapActivityList",mapActivityList);
        }
        return Res.success(paramMap.data(advMaplist));
    }
}
